package org.jeecg.modules.utils;

import java.nio.charset.StandardCharsets;

public class SendMessageUtils {

    public static int   messageSerialNo =0X11;

    public static byte[] padWithSpaces(String original, int length) {
        if (original.length() >= length) {
            return original.substring(0, length).getBytes(StandardCharsets.UTF_8);
        }
        return String.format("%-" + length + "s", original).getBytes(StandardCharsets.UTF_8);
    }

    public static String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xFF & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }

    public static int calculateCRC16(byte[] data, int offset, int length) {
        int crc = 0xFFFF;
        for (int i = offset; i < offset + length; i++) {
            crc ^= (data[i] & 0xFF);
            for (int j = 0; j < 8; j++) {
                if ((crc & 1) > 0) {
                    crc >>= 1;
                    crc ^= 0xA001;
                } else {
                    crc >>= 1;
                }
            }
        }
        return crc;
    }

}
